#include <jni.h>
#include <stdio.h>
#include "PhGA_Interface.h"
#include "../phga/phga.h"

#ifdef WEKA
//java
JNIEnv *javaenv;
jobject javaobj;
#endif

static phga* ga;

JNIEXPORT void JNICALL Java_PhGA_1Interface_setPopulation(JNIEnv *env , jobject obj, jint population)
{
	ga->setMaxPopulation(population);
}

JNIEXPORT void JNICALL Java_PhGA_1Interface_setFactor(JNIEnv *env, jobject obj, jfloat factor)
{
	ga->setFactor(factor);
}

JNIEXPORT void JNICALL Java_PhGA_1Interface_setProblemSize(JNIEnv *env, jobject obj, jint size)
{
	ga->setProblemSize(size);
}

JNIEXPORT void JNICALL Java_PhGA_1Interface_setTournamentSize(JNIEnv *env, jobject obj, jint size)
{
	ga->setTournamentSize(size);
}

JNIEXPORT void JNICALL Java_PhGA_1Interface_setSeed(JNIEnv *env, jobject obj, jint seed)
{
	ga->setSeed(seed);
}

JNIEXPORT jfloat JNICALL Java_PhGA_1Interface_run(JNIEnv *, jobject)
{
	//allocate the genetic algorithm with the parameters set before (population_size, seed, factor, etc...)
	ga->allocate();

	float fitness;

	while(ga->evolve(-1, &fitness)==true)
	{
	}

	//ga->printSimpleResult();

	//delete ga;
	
	return fitness;
}

JNIEXPORT void JNICALL Java_PhGA_1Interface_create(JNIEnv *env, jobject obj)
{
	//cache for storing the id of the Java function we are going to call back
//	static jmethodID mid;

	javaenv= env;
	javaobj=obj;

	ga= new phga();
	
	//get only some parameters from file
	ga->getParametersFromFile("parameters");
	
	ga->setWekaFitness();//env, obj);


	/*
	int i;
	int array_size= 20;
	int *chromossome= (int*)malloc(sizeof(int)*array_size);
	for(i=0; i<array_size ;i++)
	{
		chromossome[i]= 1;
	}
					
	float f= ga->testFitness(chromossome, 0, (long int)array_size);

	printf("fitness %f\n", f);
	*/


/*	
	int i=0;
	int array_size= 20;
	float *chromossome= (float*)malloc(sizeof(float)*array_size);
	for(i=0; i<array_size ;i++)
	{
		chromossome[i]= 3;
	}


	jclass cls = env->GetObjectClass(obj);
	
	if(mid==NULL)
	{
		//get method ID from java
	
		//(I)F = parameter-integer , return-float
		mid = env->GetMethodID(cls, "fitness", "([FI)F");
		
		if (mid == NULL) 
		{
			//method not found
			return; 
		}
	}
	
	printf("In C\n");


	//Create a float array
	jfloatArray java_array = env->NewFloatArray(array_size);
	if(java_array == NULL) 
	{
		return;
	}
	
	//copying the chromossome in this java_array
	env->SetFloatArrayRegion(java_array, 0, array_size, chromossome);

	
	float fitness= (env)->CallFloatMethod(obj, mid, java_array, array_size);

	printf("fitnes %f\n",fitness);

	(env)->DeleteLocalRef(java_array);
*/
	return;
}

